import Vue from "vue";
import {Toast} from 'vant';

Vue.use(Toast)

let url = 'ws://' + location.hostname + ':81/'
let ws;
let tt;
let lockReconnect = false;//避免重复连接
let handlerMap = new Map();
let websocket = {
    Init: function () {
        if ("WebSocket" in window) {
            ws = new WebSocket(url);
        } else if ("MozWebSocket" in window) {
            ws = new MozWebSocket(url);
        } else {
            Toast.fail({message: "您的浏览器不支持websocket", position: 'top'})
            return;
        }

        ws.onmessage = function (e) {
            messageHandle(e.data)
        }

        ws.onclose = function () {
            console.log("连接已关闭")
            Toast.fail({message: "websocket连接已关闭", position: 'top'})
            reconnect();
        }

        ws.onopen = function () {
            console.log("连接成功")
        }

        ws.onerror = function (e) {
            console.log("数据传输发生错误");
            Toast.fail({message: "websocket数据传输发生错误", position: 'top'})
            reconnect()
        },
            this.registerHandler("base", "log", printLog)
    },
    Send: function (data) {
        let msg = JSON.stringify(data)
        console.log("发送消息：" + msg)
        ws.send(msg)
    },
    getWebSocket() {
        return ws;
    },
    getStatus() {
        if (ws.readyState == 0) {
            return "未连接";
        } else if (ws.readyState == 1) {
            return "已连接";
        } else if (ws.readyState == 2) {
            return "连接正在关闭";
        } else if (ws.readyState == 3) {
            return "连接已关闭";
        }
    },
    registerHandler(page, cmd, func) {
        handlerMap.set(cmd + "$" + page, func)
    },
    unregisterHandler(page, cmd) {
        if (cmd)
            handlerMap.delete(cmd + "$" + page)
        else
            for (let key of handlerMap.keys()) {
                if (key.split("$")[0] == key)
                    handlerMap.delete(key)
            }
    }
}

export default websocket;

//根据消息标识做不同的处理
function messageHandle(message) {
    let data = JSON.parse(message)
    if (data.cmd) {
        for (let key of handlerMap.keys()) {
            if (key.split("$")[0] == data.cmd) {
                let func = handlerMap.get(key)
                if (typeof func === "function")
                    func(data)
            }
        }
    }
}

function printLog(data) {
    console.log(data.msg)
}

function reconnect() {
    if (lockReconnect) {
        return;
    }
    ;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    tt && clearTimeout(tt);
    tt = setTimeout(function () {
        console.log("执行断线重连...")
        websocket.Init();
        lockReconnect = false;
    }, 2000);
}


